<script setup>
import { ref, onMounted } from 'vue';

// 定义props
const props = defineProps({
  themeName: {
    type: String,
    default: 'nice'
  }
});

// 状态管理 - 简化版，确保响应式正常工作
const activeTab = ref('look'); // 当前激活的标签页
const records = ref([]); // 记录数据
const loading = ref(false); // 加载状态
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页条数
const total = ref(0); // 总记录数

// 模拟数据 - 已移除，直接使用API数据

// 首字母大写函数
const capitalizeFirstLetter = (string) => {
  return string.charAt(0).toUpperCase() + string.slice(1);
};

// 获取记录类型的文本描述
const getRecordTypeText = (type) => {
  const typeMap = {
    0: '文章',    // ARTICLE
    1: '分类',    // CATEGORY
    2: '链接',    // LINK
    3: '联系',    // CONTACT
    4: '专栏',    // COLUMN
    5: '评论',    // COMMENT
    6: '主题',    // THEME
    7: '页面'     // PAGE
  };
  return typeMap[type] || `未知(${type})`;
};

// API请求函数
const fetchFromApi = async (tab, page) => {
  try {
    console.log('发送API请求:', { tab, page });
    // 根据不同的标签调用不同的API端点
    let apiUrl = '';
    
    // 根据标签类型构建不同的API路径
    switch(tab) {
      case 'look':
        apiUrl = `/${props.themeName}/user/listLook?page=${page}&size=${pageSize.value}`;
        break;
      case 'collect':
        apiUrl = `/${props.themeName}/user/listCollect?page=${page}&size=${pageSize.value}`;
        break;
      case 'like':
        apiUrl = `/${props.themeName}/user/listLike?page=${page}&size=${pageSize.value}`;
        break;
      case 'nasty':
        apiUrl = `/${props.themeName}/user/listNasty?page=${page}&size=${pageSize.value}`;
        break;
      case 'score':
        apiUrl = `/${props.themeName}/user/listScore?page=${page}&size=${pageSize.value}`;
        break;
      case 'share':
        apiUrl = `/${props.themeName}/user/listShare?page=${page}&size=${pageSize.value}`;
        break;
      default:
        apiUrl = `/${props.themeName}/user/list${capitalizeFirstLetter(tab)}?page=${page}&size=${pageSize.value}`;
    }
    
    const response = await fetch(apiUrl, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        // 这里可以添加认证token等
        // 'Authorization': 'Bearer ' + token
      }
    });
    
    if (!response.ok) {
      throw new Error(`API请求失败: ${response.status}`);
    }
    
    const data = await response.json();
    console.log('API请求成功:', data);
    
    // 处理后端返回的数据格式
    if (data.code === 200 && data.rows && Array.isArray(data.rows)) {
      // 假设后端返回的是 TableDataInfo 格式: {code: 200, rows: [...], total: ...}
      records.value = data.rows;
      total.value = data.total || data.rows.length;
      return true; // API请求成功
    } else {
      console.warn('API返回数据格式不符合预期:', data);
      return false; // API返回数据格式不正确
    }
  } catch (error) {
    console.error('API请求出错:', error);
    return false; // API请求失败
  }
};

// 加载数据函数
const loadData = async (tab, page) => {
  console.log('加载数据:', { tab, page });
  loading.value = true;
  
  try {
    // 直接调用API获取数据，不再使用模拟数据作为备选
    const apiSuccess = await fetchFromApi(tab, page);
    
    if (apiSuccess) {
      console.log('API数据加载成功');
      currentPage.value = page;
    } else {
      console.warn('API数据加载失败，但继续使用当前数据状态');
      // 不再回退到模拟数据，保持空白状态
    }
  } catch (error) {
    console.error('加载数据出错:', error);
  } finally {
    loading.value = false;
  }
};

// 切换标签页函数
const switchTab = (tab) => {
  console.log('切换标签页:', { from: activeTab.value, to: tab });
  activeTab.value = tab;
  currentPage.value = 1;
  loadData(tab, 1);
};

// 删除记录函数
const deleteRecord = async (recordId) => {
  console.log('删除记录:', recordId);
  if (!confirm('确定要删除这条记录吗？')) return;
  
  try {
    // 尝试API删除请求
    const idField = activeTab.value === 'look' ? 'lookId' : 'recordId';
    
    // 构建删除API路径
    let apiUrl;
    if (activeTab.value === 'look') {
      apiUrl = `/${props.themeName}/user/removeLook/${recordId}`;
    } else {
      apiUrl = `/${props.themeName}/user/removeRecord/${recordId}`;
    }
    
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // 这里可以添加认证token等
        // 'Authorization': 'Bearer ' + token
      }
    });
    
    const data = await response.json();
    
    // 检查后端返回的AjaxResult格式
    if (response.ok && data.code === 200) {
      // API删除成功
      console.log('记录删除成功（API）:', data);
      alert('删除成功');
      // 重新加载数据
      loadData(activeTab.value, currentPage.value);
    } else {
      // API删除失败，尝试从本地模拟数据中删除
      console.log('API删除失败，尝试从本地模拟数据中删除');
      const tabData = mockData[activeTab.value];
      if (tabData) {
        const index = tabData.findIndex(item => item[idField] === recordId);
        
        if (index !== -1) {
          tabData.splice(index, 1);
          loadData(activeTab.value, currentPage.value);
          alert('删除成功（模拟数据）');
        } else {
          alert('记录不存在或已被删除');
        }
      }
    }
  } catch (error) {
    console.error('删除记录出错:', error);
    // 出错时尝试从本地模拟数据中删除
    const tabData = mockData[activeTab.value];
    if (tabData) {
      const idField = activeTab.value === 'look' ? 'lookId' : 'recordId';
      const index = tabData.findIndex(item => item[idField] === recordId);
      
      if (index !== -1) {
        tabData.splice(index, 1);
        loadData(activeTab.value, currentPage.value);
        alert('删除成功（模拟数据）');
      } else {
        alert('记录不存在或已被删除');
      }
    }
  }
};

// 处理页码变化
const handlePageChange = (page) => {
  console.log('页码变化:', { from: currentPage.value, to: page });
  // 更新当前页码
  currentPage.value = page;
  // 加载对应页码的数据
  loadData(activeTab.value, page);
};

// 计算总页数
const totalPages = () => {
  return Math.ceil(total.value / pageSize.value);
};

// 组件挂载时加载初始数据
onMounted(() => {
  console.log('组件挂载完成，加载初始数据');
  loadData(activeTab.value, 1);
});
</script>

<template>
  <div class="bg-white dark:bg-gray-900 rounded-lg shadow-md p-4">
    <!-- 标签页切换 -->
    <div class="flex border-b border-gray-200 dark:border-gray-700 mb-4">
      <button 
        v-for="(tab, index) in ['look', 'collect', 'like', 'nasty', 'score', 'share']"
        :key="tab"
        @click="switchTab(tab)"
        :class="[
          'py-4 px-1 border-b-2 text-sm font-medium',
          activeTab === tab 
            ? 'border-blue-500 text-blue-600 dark:text-blue-400'
            : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:border-gray-300 dark:hover:border-gray-600'
        ]"
      >
        {{ ['浏览记录', '收藏记录', '喜欢记录', '讨厌记录', '评分记录', '分享记录'][index] }}
      </button>
    </div>

    <!-- 数据展示区 -->
    <div v-if="loading" class="py-8 text-center text-gray-500">
      加载中...
    </div>
    <div v-else-if="records.length === 0" class="py-8 text-center text-gray-500">
      暂无记录
    </div>
    <div v-else class="space-y-3">
      <div 
        v-for="record in records" 
        :key="activeTab === 'look' ? record.lookId : record.recordId"
        class="flex items-center justify-between p-3 border border-gray-200 dark:border-gray-700 rounded-md hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
      >
        <div class="flex-1">
          <div class="flex flex-wrap gap-2 items-center">
            <span class="text-sm text-gray-500">
              ID: {{ activeTab === 'look' ? record.lookId : record.recordId }}
            </span>
            <span class="text-xs px-2 py-0.5 bg-gray-100 dark:bg-gray-700 rounded">
              类型: {{ getRecordTypeText(record.recordType) }}
            </span>
          </div>
          <p class="text-sm text-gray-500 mt-2">
            <span>创建时间: {{ record.createTime }}</span>
            <span v-if="record.score" class="ml-3">评分: {{ record.score }}</span>
            <span v-if="record.shareUrl" class="ml-3">分享链接: {{ record.shareUrl }}</span>
          </p>
          <div v-if="activeTab === 'look'" class="text-xs text-gray-400 mt-1">
            <span v-if="record.ip">IP: {{ record.ip }}</span>
            <span v-if="record.userSystem" class="ml-2">系统: {{ record.userSystem }}</span>
            <span v-if="record.userBower" class="ml-2">浏览器: {{ record.userBower }}</span>
          </div>
        </div>
        <button 
          @click="deleteRecord(activeTab === 'look' ? record.lookId : record.recordId)"
          class="px-3 py-1 bg-red-100 dark:bg-red-900 text-red-600 dark:text-red-400 rounded text-sm hover:bg-red-200 dark:hover:bg-red-800 transition-colors"
        >
          删除
        </button>
      </div>
    </div>

    <!-- 分页控件 - 优化版本 -->
    <div v-if="total > 0 && totalPages() > 1" class="flex items-center justify-center gap-3 mt-6 py-3 border-t">
      <!-- 上一页按钮 -->
      <button 
        v-if="currentPage > 1"
        @click="handlePageChange(currentPage - 1)"
        class="px-4 py-2 border rounded-md text-sm hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors flex items-center gap-1"
        title="上一页"
      >
        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
        </svg>
        上一页
      </button>
      
      <!-- 页码显示 -->
      <span class="px-4 py-2 bg-gray-50 dark:bg-gray-800 border rounded-md text-sm font-medium">
        {{ currentPage }} / {{ totalPages() }}
      </span>
      
      <!-- 下一页按钮 -->
      <button 
        v-if="currentPage < totalPages()"
        @click="handlePageChange(currentPage + 1)"
        class="px-4 py-2 border rounded-md text-sm hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors flex items-center gap-1"
        title="下一页"
      >
        下一页
        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
        </svg>
      </button>
    </div>
  </div>
</template>

<style scoped>
/* 确保按钮有适当的光标样式 */
button {
  cursor: pointer;
}
</style>